<template>
  <div class="to-top" v-show="isShow" @click="back" v-back-to-top="toggle">
    顶部
  </div>
</template>

<script>
export default {
  name: "ToTop",
  data() {
    return {
      isShow: false
    };
  },
  directives: {
    backToTop: {
      inserted(el, binding) {
        document.querySelector("main>div").addEventListener(
          "scroll",
          e => {
            binding.value(e.target.scrollTop > 900);
          },
          false
        );
      }
    }
  },
  methods: {
    back() {
      var ids = setInterval(function() {
        let speed = Math.floor(
          -document.querySelector("main>div").scrollTop / 5
        );
        document.querySelector("main>div").scrollTop += speed;
        if (document.querySelector("main>div").scrollTop === 0) {
          clearInterval(ids);
        }
      }, 30);
    },
    toggle(show) {
      this.isShow = show;
    }
  }
};
</script>

<style lang="scss" scoped>
.to-top {
  position: fixed;
  bottom: 80px;
  right: 20px;
  background: #31a5fc;
  color: #fff;
  width: 44px;
  height: 44px;
  text-align: center;
  line-height: 44px;
  border-radius: 30px;
  font-size: 12px;
}
</style>
